﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Globalization;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel;

namespace audioCheck
{
    public partial class Form1 : Form
    {
        string path_excel;
        string path_guid;
        private List<List<string>> curDataList;
        private List<List<string>> curGuidList;

        // AudioKey  对应AssetName  最后的实际名称
        private Dictionary<string, string> audioDicKeyEvent = new Dictionary<string, string>();

        // guid  AssetName  最后的实际名称 对应的当前 AssetName
        private Dictionary<string, string> audioGuidKey = new Dictionary<string, string>();

        // 最终导出有问题的内容
        private List<List<string>> needOutList;  //

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 执行读取的是 xls 文件   xlsx 有问题哎
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SelectXlse_Click(object sender, EventArgs e)
        {
            audioDicKeyEvent.Clear();
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "所有文件(*xls*)|*.xls*"; //设置要选择的文件的类型
            fileDialog.ShowDialog();
            path_excel = fileDialog.FileName;
            lab_path1.Text = path_excel;

            var list = this.ReadExcel(path_excel);
            if (list != null && list.Count > 0)
            {
                curDataList = list;
            }
        }

        /// <summary>
        /// 取 guid 文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_SelectGUID_Click(object sender, EventArgs e)
        {
            audioGuidKey.Clear();
            OpenFileDialog fileDialog = new OpenFileDialog();
            fileDialog.Multiselect = true;
            fileDialog.Title = "请选择文件";
            fileDialog.Filter = "所有文件(*txt*)|*.txt*"; //设置要选择的文件的类型
            fileDialog.ShowDialog();
            path_guid = fileDialog.FileName;
            lab_path2.Text = path_guid;

            var list = this.ReadText(path_guid);

            if (list != null && list.Count > 0)
            {
                curGuidList = list;
            }
        }

        private void btn_out_Click(object sender, EventArgs e)
        {
            saveFileDialog_1.AddExtension = true;
            saveFileDialog_1.Filter = "audio(*.xlsx)|*.xlsx|audio(*.xls)|*.xls";
            saveFileDialog_1.ShowDialog();
        

            string path = saveFileDialog_1.FileName;
            if (string.IsNullOrEmpty(path))
            {
                return;
            }
            // 头
            List<List<string>> headers = new List<List<string>>();
            var list1 = new List<string>();
            list1.Add("AudioKey");
            list1.Add("oldAssetName");
            list1.Add("newAssetName");
            
            headers.Add(list1);

            var list2 = new List<string>();
            list2.Add("声音标识");
            list2.Add("旧的声音名字");
            list2.Add("新的声音名字");
            headers.Add(list2);


            // 数据
            List<List<string>> datas = new List<List<string>>();  //this.GetOutList();
          

            this.SaveExcel(path, headers, datas);
        }

        /// <summary>
        /// 读取Excel配置
        /// </summary>
        private List<List<string>> ReadExcel(string openPath, string sheetName = null)
        {
            var datas = new List<List<string>>();
            if (!File.Exists(openPath)) return datas;
            try
            {
                using (var fs = new FileStream(openPath, FileMode.Open))
                {
                    IWorkbook workbook = null;
                    // 2007版本  
                    if (openPath.IndexOf(".xlsx") > 0)
                        workbook = new XSSFWorkbook(fs);
                    // 2003版本  
                    else if (openPath.IndexOf(".xls") > 0)
                        workbook = new HSSFWorkbook(fs);
                    else
                        workbook = new HSSFWorkbook(fs);
                    if (workbook.NumberOfSheets > 0)
                    {
                        var sheet = string.IsNullOrEmpty(sheetName) ? workbook.GetSheetAt(0) : workbook.GetSheet(sheetName);
                        if (sheet != null && sheet.LastRowNum > 0)
                        {
                            ICell cell = null;
                            IRow firstRow = sheet.GetRow(0);//第一行  
                            int cellCount = 4; // firstRow.LastCellNum;//列数
                            // 行数从第 7 开始
                            for (var rownum = 7; rownum <= sheet.LastRowNum; rownum++)
                            {
                                try
                                {
                                    string _val_ = "";
                                    var row = sheet.GetRow(rownum);
                                    if (row == null)
                                    {
                                        continue;
                                    }
                                    cell = row.GetCell(0);
                                    if (cell == null)
                                    {
                                        continue;
                                    }
                                    else
                                    {
                                        _val_ = cell.StringCellValue;
                                        if (string.IsNullOrEmpty(_val_))
                                        {
                                            continue;
                                        }
                                    }
                                    var data = new List<string>();
                                    for (int j = 0; j < cellCount; ++j)
                                    {
                                        try
                                        {
                                            cell = row.GetCell(j);
                                            if (cell == null)
                                            {
                                                _val_ = "";
                                            }
                                            else
                                            {
                                                _val_ = "";
                                                try
                                                {
                                                    switch (cell.CellType)
                                                    {
                                                        case CellType.Numeric:
                                                            _val_ = cell.NumericCellValue.ToString(CultureInfo.InvariantCulture);
                                                            break;

                                                        case CellType.Boolean:
                                                            _val_ = cell.BooleanCellValue.ToString(CultureInfo.InvariantCulture);
                                                            break;

                                                        case CellType.String:
                                                            _val_ = cell.StringCellValue;
                                                            break;

                                                        default:
                                                            _val_ = cell.StringCellValue;
                                                            break;
                                                    }
                                                }
                                                catch (Exception e)
                                                {
                                                    _val_ = "";
                                                }
                                            }
                                            data.Add(_val_);
                                            /*
                                            data.Add(cell.CellType == CellType.Numeric
                                                ? cell.NumericCellValue.ToString(CultureInfo.InvariantCulture)
                                                : cell.StringCellValue);
                                                */
                                        }
                                        catch (Exception e)
                                        {
                                            Console.Write(e.StackTrace);
                                            Console.Write("提示", "请先关闭Excel文件:" + openPath, "OK");
                                            return null;
                                        }
                                    }
                                    if (data.Count > 2)
                                    {
                                        string eventName = data[2];
                                        if (string.IsNullOrEmpty(eventName) == false)
                                        {
                                            string[] temp = eventName.Split('/');
                                            string key = temp[temp.Length-1];
                                            audioDicKeyEvent[key] = eventName;
                                        }
                                    }
                                   

                                    datas.Add(data);
                                }
                                catch (Exception e)
                                {
                                    Console.Write(e.StackTrace);
                                    Console.Write("提示", "请先关闭Excel文件:" + openPath, "OK");
                                    return null;
                                }
                            }
                        }
                    }
                    fs.Close();
                    fs.Dispose();
                }
            }
            catch (Exception e)
            {
               
                Console.Write("提示", "请先关闭Excel文件:" + openPath, "OK");
                return null;
            }
            return datas;
        }

        /// <summary>
        /// 保存配置
        /// </summary>
        private void SaveExcel(string savePath,List<List<string>> headers,List<List<string>> datas)
        {
            if (File.Exists(savePath))
            {
                return;
            }
            XSSFWorkbook workbook = null;
            if (savePath.LastIndexOf(".xlsx") > 0)  // 2007
            {
                workbook = new XSSFWorkbook();   // 2003
            }
            //if (savePath.LastIndexOf(".xls") > 0)
            //{
            //    workbook = new HSSFWorkbook();
            //}
            //else
            //{
            //    workbook = new HSSFWorkbook();
            //}

            ISheet sheet;   // 配置表 sheet
            var appendRow = 0;   // 列

            sheet = workbook.CreateSheet("export");  // 
            sheet.DefaultColumnWidth = 40;

            // 数据头插到数据前面
            datas.InsertRange(0,headers);

            foreach (List<string> values in datas)
            {
                var row = sheet.CreateRow(appendRow);
                var cellnum = 0;  // 行
                foreach (string value in values)
                {
                    var cell = row.CreateCell(cellnum);
                    cell.SetCellValue(value);
                    cellnum++;
                }
                appendRow++;
            }

            FileStream fs = null;
            try
            {
                fs = new FileStream(savePath, FileMode.OpenOrCreate);
                if (fs.CanWrite)
                {
                    workbook.Write(fs);
                    workbook.Close();
                }
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                
            }
            MessageBox.Show("导出成功");
        }


        private List<List<string>> ReadText(string openPath)
        {
            var datas = new List<List<string>>();
            if (!File.Exists(openPath)) return datas;
            try
            {
                using (var fs = new FileStream(openPath, FileMode.Open))
                {
                    int fsLen = (int)fs.Length;
                    byte[] txtByte = new byte[fsLen];
                    int r = fs.Read(txtByte,0, txtByte.Length);
                    string myStr = System.Text.Encoding.UTF8.GetString(txtByte);
                    string[] curRowStr = myStr.Split('\r','\n');
                    for (int i = 0; i < curRowStr.Length; i++)
                    {
                        if (string.IsNullOrEmpty(curRowStr[i]) == false)
                        {
                            string[] curList = curRowStr[i].Split('}');
                            string eventName = curList[1].Trim();
                            string[] temp = eventName.Split('/');
                            string key = temp[temp.Length-1];
                            audioGuidKey[key] = eventName;
                        }
                        
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }



            return datas;
        }

        /// <summary>
        /// 需要导出的问题数据
        /// </summary>
        /// <returns></returns>
        private List<List<string>> GetOutList()
        {
            var datas = new List<List<string>>();

            if (this.audioDicKeyEvent.Count > 0 && this.audioGuidKey.Count > 0)
            {
                for (int i = 0; i < curDataList.Count; i++)
                {
                    var curData = curDataList[i];
                    // 有问题的才添加到列表中
                    string curKey = this.GetAssetNameKey(curData[2]);
                    string oldName = this.audioDicKeyEvent[curKey];
                    if (string.IsNullOrEmpty(oldName) == false)
                    {
                        // guid 上最新的 name
                        
                        if (this.audioGuidKey.ContainsKey(curKey))
                        {
                            string guidVal = this.audioGuidKey[curKey];
                            if (string.IsNullOrEmpty(guidVal) == false && oldName != guidVal)
                            {
                                List<string> data = new List<string>();
                                //标识
                                //旧name
                                // 新 name
                                data.Add(curData[0]);
                                data.Add(oldName);
                                data.Add(guidVal);
                                datas.Add(data);
                            }
                        }
                    }

                }
            }
            return datas;
        }

        /// <summary>
        /// 取 AssetName 最后一位做key
        /// </summary>
        /// <param name="eventName"></param>
        /// <returns></returns>
        private string GetAssetNameKey(string eventName)
        {
            string outKey = string.Empty;
            string[] temp = eventName.Split('/');
            outKey = temp[temp.Length - 1];
            return outKey;
        }


        List<List<string>> outList = new List<List<string>>();
        private void btn_GetChange_Click(object sender, EventArgs e)
        {
            this.outList.Clear();
            string path = text_path.Text;

            //this.GetFile(path);

            List<List<string>> header = new List<List<string>>();

            List<string> list1 = new List<string>();
            list1.Add("文件路径");
            list1.Add("文件名称");
            header.Add(list1);
            //outList.InsertRange(0, header);

            saveFileDialog_1.AddExtension = true;
            saveFileDialog_1.Filter = "audio(*.xlsx)|*.xlsx|audio(*.xls)|*.xls";
            saveFileDialog_1.ShowDialog();


            string savePath = saveFileDialog_1.FileName;
            if (string.IsNullOrEmpty(savePath))
            {
                return;
            }
            //this.SaveListToExcel(savePath, outList);
            this.SaveExcel(savePath, header, this.outList);

        }

        private void GetFile(string path)
        {

            // 遍历路径下json 
            // 对比name 如果一样
            // 修改里面 的bundleName 然后保存
            DirectoryInfo TheFolder = new DirectoryInfo(path);

            DirectoryInfo[] curAllNextFolder = TheFolder.GetDirectories();

            foreach (var NextFolder in curAllNextFolder)
            {

                DirectoryInfo[] directory = NextFolder.GetDirectories();
                FileInfo[] fileInfos = NextFolder.GetFiles();
                if (fileInfos.Length > 0)
                {
                    foreach (var file in fileInfos)
                    {
                        this.GetFileName(file.FullName);
                    }
                }
                if (directory.Length > 0)
                {
                    foreach (var item in directory)
                    {
                        this.GetFile(item.FullName);
                    }
                }
            }

            FileInfo[] curfileInfos = TheFolder.GetFiles();
            if (curfileInfos.Length > 0)
            {
                foreach (var file in curfileInfos)
                {
                    this.GetFileName(file.FullName);
                }
            }

        }
        private void GetFileName(string path)
        {
            if (string.IsNullOrEmpty(path) == false && path.Contains(".json") && path.Contains(".meta") == false)
            {
                string jsonFile = path;
                StringBuilder outToStr = new StringBuilder();
                using (var fs = new FileStream(jsonFile, FileMode.Open))
                {
                    int fsLen = (int)fs.Length;
                    byte[] txtByte = new byte[fsLen];
                    int r = fs.Read(txtByte, 0, txtByte.Length);
                    string myStr = System.Text.Encoding.UTF8.GetString(txtByte);
                    if (myStr.Contains("bundleName=\"scene\""))
                    {
                        List<string> list = new List<string>();
                        list.Add(path);
                        string[] temp = path.Split('\\');
                        string name = temp[temp.Length -1];
                        list.Add(name);
                        string[] temp2 = name.Split('.');
                        string filnename = temp2[0];
                        list.Add(filnename);
                        this.outList.Add(list);
                    }
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
    }
}
